package com.peng.ppscalelibrary.BleManager.util;

import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.utils.BluetoothLog;
import com.inuker.bluetooth.library.utils.BluetoothUtils;
import com.inuker.bluetooth.library.utils.ByteUtils;
import com.peng.ppscalelibrary.BleManager.Model.BleAdvertisedData;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class BleUtil {
    private final static String TAG=BleUtil.class.getSimpleName();

    public static String getName(SearchResult device) {

        if (device.getName().equals("NULL")){
            Beacon beacon = new Beacon(device.scanRecord);
            BleAdvertisedData data = BleUtil.parseAdertisedData(beacon.mBytes);
            BluetoothLog.v("getAdvName----" + data.getName());
            return data.getName();
        }else{
            BluetoothLog.v("getName----" + device.getName());
            return device.getName();
        }
    }


    public static BleAdvertisedData parseAdertisedData(byte[] advertisedData) {
        BluetoothLog.v("parseAdertisedData " + ByteUtils.byteToString(advertisedData));
        List<UUID> uuids = new ArrayList<UUID>();
        String name = "";
        if( advertisedData == null ){
            return new BleAdvertisedData(uuids, name);
        }

        ByteBuffer buffer = ByteBuffer.wrap(advertisedData).order(ByteOrder.LITTLE_ENDIAN);
        while (buffer.remaining() > 2) {
            byte length = buffer.get();
            if (length == 0) break;

            byte type = buffer.get();
            switch (type) {
                case 0x09:
                    byte[] nameBytes = new byte[length-1];
                    buffer.get(nameBytes);
                    try {
                        name = new String(nameBytes, "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
//                    buffer.position(buffer.position() + length - 1);
                    break;
            }
        }
        return new BleAdvertisedData(uuids, name);
    }
}

